# import pytest
from selenium import webdriver
import unittest, time
from contrast import ImageCompare
# from ddt import ddt,data
from public import *
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import shutil
import datetime
import logging
from logger import *
import os
# from PIL import ImageGrab
import requests
import xlrd,xlwt
from xlutils.copy import copy
from test_send_email import *

# class TestAutomation:
import sys
sys.setrecursionlimit(10000)

def set_sum(i):
    sum = i
    return sum


file_name =None
def create_excel(d):
    global file_name
    ws = xlwt.Workbook()
    sheet = ws.add_sheet("CBCT曝光上传")
    sheet.write(0,0,'虚拟驱动自动化测试')
    sheet.write(0, 1, "设置运行次数")
    sheet.write(1, 1, "{}".format(d))
    sheet.write(2, 1, "{}".format(d))
    sheet.write(3, 1, "{}".format(d))
    sheet.write(0, 2, "实际运行次数")
    sheet.write(0, 3, "上传成功次数")
    sheet.write(0, 4, "上传失败次数")
    sheet.write(0, 5, "卡住次数")
    sheet.write(1, 0, "CT上传")
    sheet.write(2, 0, "PX上传")
    sheet.write(3, 0, "DX上传")
    file_name =".\\reports\\CBCT_上传测试{}.xls".format(time.strftime('%Y-%m-%d-%H'))
    ws.save(file_name)


def write_excel(a,b,value):
    data = xlrd.open_workbook(file_name)
    workbook = copy(data)
    sheet_write = workbook.get_sheet(0)
    value = str(value)
    sheet_write.write(a,b,value)
    workbook.save(file_name)



def login_():
    driver = webdriver.Chrome()
    driver.get('http://127.0.0.1:8189/#/')
    driver.maximize_window()
    driver.find_element_by_xpath('//input[@class="yg-input__inner" and @placeholder="请输入手机号"]').send_keys("19973877211")  # 输入手机号
    driver.find_element_by_xpath('//input[@class="yg-input__inner" and @placeholder="请输入密码"]').send_keys('111111111')  # 输入密码
    driver.find_element_by_xpath('//div[@class="zh_postForm"]').click()  # 点击登录
    return driver

# global i


ct_a =0 #上传成功
ct_b =0 #上传失败
ct_c =0 #准备进度卡住


def test_01_CT_shooting(i,c):
    logging.info('CT开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('test_01_CT_shooting第{}次'.format(i))
    write_excel(1,2,i)
    if c:
        driver = c
        # logging.info('test_01_CT_shooting_第{}次'.format(i))
        time.sleep(8)
        driver.find_element_by_xpath('//div[text()="登记"]').click()  # 进入登记页
        time.sleep(1)
        patient_name = random_name() + '{}'.format(i)
        driver.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name))  # 输入患者姓名参数化
        time.sleep(1)
        driver.find_element_by_xpath('//div[@id="cbctCT"]').click()  # 选择拍摄模式
        driver.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  # 点击下一步
        time.sleep(1)
        driver.find_element_by_xpath('//button[@class="ok-btn userSelect bianseBorder"]').click()  # 点击确确定

        try:
            progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  # 等待准备完成元素可见
            WebDriverWait(driver, 90, 1).until(EC.visibility_of_element_located(progress_locator))
            time.sleep(1)
            driver.find_element_by_xpath('//div[@id="cbctFinishct"]').click()  # CT点击下一步

            shutil.copy('D:\\HandSwitchOn.txt', 'D:\\CTDebug')  # 复制手闸文件到CTDebug目录
            time.sleep(150)  # 等待采集曝光完成
            filepath = 'D:\\ycw\\CTscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
            driver.save_screenshot(filepath)
            time.sleep(3)
            driver.find_element_by_xpath('//span[@class="nsel close-btn"]').click()  # CT叉掉元素
            time.sleep(5)
            driver.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
            try:
                loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
                if WebDriverWait(driver, 300, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
                    logging.info('CT上传成功')
                    global ct_a
                    ct_a += 1
                    write_excel(1, 3, ct_a)
            except:
                logging.info('CT上传失败')
                global ct_b

                ct_b += 1
                write_excel(1, 4, ct_b)

            logging.info('CT结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            return driver
        except:
            error_filepath = 'D:\\ycw\\CTscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
            driver.save_screenshot(error_filepath)
            global ct_c
            ct_c +=1
            write_excel(1,5,ct_c)
            logging.error("CT{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            # driver.quit()




px_a =0
px_b =0
px_c =0 #准备进度卡住


def test_02_Panoramic_shooting(i,a):
    driver2 = a
    logging.info('PX开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('PX第{}次'.format(i))
    write_excel(2,2,i)
    time.sleep(5)
    driver2.find_element_by_xpath('//div[text()="登记"]').click()
    time.sleep(1)
    patient_name2 = random_name() + '{}'.format(i)
    driver2.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name2))  # 输入患者姓名参数化
    driver2.find_element_by_xpath('//div[@id="cbctPX"]').click() #全景模式
    driver2.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()   # 选择模式后的下一步
    time.sleep(3)
    driver2.find_element_by_xpath('//button[@id="cbctOkpano"]').click()  #点击确定
    '''去曝光'''
    try:
        # time.sleep(60)
        progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  #等待准备完成元素可见
        WebDriverWait(driver2,150,1).until(EC.visibility_of_element_located(progress_locator))
        time.sleep(1)
        driver2.find_element_by_xpath('//div[@id="cbctFinishceph"]').click()  #全景下一步
        time.sleep(3)
        driver2.find_element_by_xpath('//div[@id="cbctkspano"]').click()  # 点击开始按钮
        time.sleep(2)
        shutil.copy('D:\\HandSwitchOn.txt', 'D:\\CTDebug')
        time.sleep(100)    #全景曝光与采集时间

        px_object = (By.XPATH,'//div[contains(text()," 全景图像后处理完成，采集结束")]')
        WebDriverWait(driver2,100,1).until(EC.visibility_of_element_located(px_object))
        time.sleep(10)
        filepath = 'D:\\ycw\\PXscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
        driver2.save_screenshot(filepath)
        driver2.find_element_by_xpath('//div[@id="cbctbcpano"]').click()  # 全景对勾元素确定
        time.sleep(8)
        driver2.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
        try:
            loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
            if WebDriverWait(driver2,135, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
                logging.info('PX上传成功')
                global px_a
                px_a += 1
                write_excel(2, 3, px_a)
        except:
            global px_b
            px_b += 1
            write_excel(2, 4, px_b)
            logging.info('PX上传失败')
        logging.info('PX结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        return driver2

    except:
        error_filepath = 'D:\\ycw\\PXscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        driver2.save_screenshot(error_filepath)
        global px_c
        px_c += 1
        write_excel(2, 5, px_c)
        logging.error("PX{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        # driver2.quit()


    # 头侧拍摄


dx_a =0
dx_b =0
dx_c =0  #准备进度卡住


def test_03_Head_side_shot(i,b):

    drive3 = b
    logging.info('DX开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('DX第{}次'.format(i))
    write_excel(3,2,i)
    time.sleep(5)
    drive3.find_element_by_xpath('//div[text()="登记"]').click()
    time.sleep(1)
    patient_name3 = random_name() + '{}'.format(i)
    drive3.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name3)) # 输入患者姓名参数化
    drive3.find_element_by_xpath('//div[@id="cbctDX"]').click()  #头测模式
    drive3.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  #选择模式下的下一步
    time.sleep(3)
    drive3.find_element_by_xpath('//button[@id="cbctOkceph"]').click() #确定按钮
    try:
        progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  #等待准备完成元素可见
        WebDriverWait(drive3,150,1).until(EC.visibility_of_element_located(progress_locator))
        time.sleep(1)
        drive3.find_element_by_xpath('//div[@id="cbctFinishceph"]').click()  # 头测点下一步
        time.sleep(3)
        # 判断放手闸的提示语元素
        shutil.copy('D:\\HandSwitchOn.txt','D:\\CTDebug')
        time.sleep(100)     # 头测曝光与采集时间

        px_object = (By.XPATH,'//div[contains(text(),"头侧图像后处理完成，采集结束")]')
        WebDriverWait(drive3,100,1).until(EC.visibility_of_element_located(px_object))
        time.sleep(10)
        filepath = 'D:\\ycw\\DXscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        drive3.save_screenshot(filepath)
        drive3.find_element_by_xpath('//div[@id="cbctbcceph"]').click()  # 点击头测对勾元素确定
        time.sleep(8)
        drive3.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
        try:
            loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
            if WebDriverWait(drive3, 30, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
                logging.info('DX上传成功')
                global dx_a
                dx_a+=1
                write_excel(3,3,dx_a)
        except:
            logging.info('DX上传失败')
            global dx_b
            dx_b += 1
            write_excel(3, 4, dx_b)
        logging.info('DX结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        return drive3

    except:
        error_filepath = 'D:\\ycw\\DXscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        drive3.save_screenshot(error_filepath)
        global dx_c
        dx_c += 1
        write_excel(3, 5, dx_c)
        logging.error("DX{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        # drive3.quit()


if __name__ == '__main__':
    f = open('./gggg')
    d = f.read()
    d = int(d)
    create_excel(d)
    start_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    write_excel(4,0,"开始时间")
    write_excel(4,1,start_time)
    num = 20
    try:
        for x in range(d//num):
            c = login_()
            for i in range(num):
                if c:
                     a = test_01_CT_shooting(x*num+i+1,c)
                else:
                    break
                    # c.quit()
                if c:
                   c = test_02_Panoramic_shooting(x*num+i+1,c)
                else:
                    # c.quit()
                   break

                if c:
                   c = test_03_Head_side_shot(x*num+i+1,c)
                else:
                    # c.quit()
                   break
            if c != None:
                c.close()
            else:
                pass
    except Exception as e:
        logging.info(e)
    finally:
        finally_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        write_excel(5,0,"停止时间")
        write_excel(5,1,finally_time)

        yag = yagmail.SMTP(user="1425491509@qq.com", password="ikbfjwjsbqhsieih", host='smtp.qq.com')


        rev_email1 = '1425491509@qq.com'
        rev_email2 = 'liang.ding@fussenct.com'
        title = '【虚拟驱动】发送附件CBCT测试结果'
        contents = ['【虚拟驱动】对面CBCT压力稳定性结果统计']
        file_path = FindNewFile().get_new_file('.\\reports')
        file_path2 = FindNewFile().get_new_file('.\\logs')

        # yag.send() #收件人邮箱 标题 正文 附件地址
        # yag.send([rev_email1,rev_email2 ],title, contents, [file_path, file_path2])

        # yag.send(rev_email1,title, contents, [file_path, file_path2])
